package com.situ.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.situ.bean.APIResult;
import com.situ.bean.Dept;
import com.situ.service.DeptService;

@RestController
@RequestMapping("/api/depts")
@CrossOrigin(origins = { "http://127.0.0.1:8848" }) // 允许跨域访问()
public class DeptController {

	@Autowired
	private DeptService deptService;

	@PostMapping
	@ResponseStatus(code = HttpStatus.CREATED) // 设置返回的HTTP的状态码
	public APIResult add(@RequestBody Dept dept) {// @RequestBody 把在前带端页面传过来的json格式转换再注入
		dept = deptService.add(dept);
		APIResult result = new APIResult();
		result.setStatus(201);
		result.setData(dept);
		return result;

	}

	@DeleteMapping
	@ResponseStatus(code = HttpStatus.OK)
	public APIResult remove(Integer id) {
		Dept dept = deptService.remove(id);
		APIResult result = new APIResult();
		if (dept != null) {
			result.setStatus(204);
			result.setData(dept);
		} else {
			result.setStatus(404);
			result.setMsg("删除的部门不存在");
		}
		return result;
	}

	@PutMapping
	@ResponseStatus(code = HttpStatus.CREATED)
	public APIResult edit(@RequestBody Dept dept) {
		dept = deptService.edit(dept);
		APIResult result = new APIResult();
		if (dept != null) {
			result.setStatus(201);
			result.setData(dept);
		} else {
			result.setStatus(404);
			result.setMsg("修改的部门不存在");
		}
		return result;
	}

	@GetMapping("/{id}")
	public APIResult get(@PathVariable("id") Integer id) {

		Dept dept = deptService.getById(id);
		APIResult result = new APIResult();
		if (dept == null) {

			result.setStatus(404);
			result.setMsg("部门不存在");
		} else {
			result.setStatus(200);
			result.setData(dept);
		}
		return result;
	}

	@GetMapping
	public APIResult get() {
		List depts = deptService.getAll();
		APIResult result = new APIResult();
		if (depts != null && depts.size() > 0) {
			result.setStatus(200);
			result.setData(depts);
		} else {
			result.setStatus(404);
			result.setMsg("未找到任何记录");
		}
		return result;
	}
}
